import { createRouter, createWebHistory } from 'vue-router'

// 动态导入组件，避免路径问题
const Login = () => import('../pages/login/login.vue')
const Hall = () => import('../pages/hall/hall.vue')
const Orders = () => import('../pages/orders/orders.vue')
const OrderDetail = () => import('../pages/order-detail/detail.vue')
const Profile = () => import('../pages/profile/profile.vue')

const routes = [
  {
    path: '/',
    redirect: '/pages/login/login'
  },
  {
    path: '/pages/login/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false // 登录页面不需要认证
    }
  },
  {
    path: '/pages/hall/hall',
    name: 'Hall',
    component: Hall,
    meta: {
      requiresAuth: true // 需要认证
    }
  },
  {
    path: '/pages/orders/orders',
    name: 'Orders',
    component: Orders,
    meta: {
      requiresAuth: true // 需要认证
    }
  },
  {
    path: '/pages/order-detail/detail',
    name: 'OrderDetail',
    component: OrderDetail,
    meta: {
      requiresAuth: true // 需要认证
    }
  },
  {
    path: '/pages/profile/profile',
    name: 'Profile',
    component: Profile,
    meta: {
      requiresAuth: true // 需要认证
    }
  }
]

// 使用工厂函数创建路由实例，避免重复创建
let routerInstance = null

function createRouterInstance() {
  if (!routerInstance) {
    routerInstance = createRouter({
      history: createWebHistory(),
      routes
    })
    
    // 添加路由守卫
    routerInstance.beforeEach((to, from, next) => {
      // 检查是否需要认证
      if (to.meta.requiresAuth) {
        // 检查用户是否已登录
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo && userInfo.userId) {
          // 已登录，允许访问
          next()
        } else {
          // 未登录，重定向到登录页面
          console.log('路由守卫：用户未登录，重定向到登录页面')
          next({
            path: '/pages/login/login',
            query: { redirect: to.fullPath } // 保存原本要访问的页面，登录后可以跳转回去
          })
        }
      } else {
        // 不需要认证的页面，直接访问
        next()
      }
    })
  }
  return routerInstance
}

export default createRouterInstance()